package org.xiezc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * 错误拦截类, 当请求出错之后会拦截错误信息, 并跳转到error 页面
 * create by xiezc on 17/1/16 11:55:21.
 *
 */
public class ExceptionFilter implements Filter {

    private static Logger logger = Logger.getLogger(ExceptionFilter.class);

    @Override
    public void destroy() {
        logger.info("ExceptionFilter already destroy");
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;
        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            // String url = request.getRequestURI();
            request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        logger.info("ExceptionFilter; initialize");
    }
}
